<template>
  <div class="main member-list">
    <div class="filter-container">
      <el-input @keyup.enter.native="search" class="filter-item" placeholder="按手机号搜索" v-model="params.search"></el-input>
      <el-select v-model="params.currentMemberCardType" clearable placeholder="请选择会员等级" class="filter-item">
        <el-option label="所有等级" value=""></el-option>
        <el-option v-for="(name, val) in levels" :key="val" :label="name" :value="val"></el-option>
      </el-select>
      <el-input @keyup.enter.native="search" class="filter-item" placeholder="碧选昵称" v-model="params.nickname"></el-input>
      <el-input @keyup.enter.native="search" class="filter-item" placeholder="姓名" v-model="params.realName"></el-input>
      <el-select v-model="params.deleteFlag" clearable placeholder="用户状态" class="filter-item">
        <el-option label="全部" value=""></el-option>
        <el-option :key="1" label="正常" :value="1"></el-option>
        <el-option :key="0" label="禁用" :value="0"></el-option>
        <el-option :key="2" label="注销" :value="2"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
      <el-button v-if="rightsButtons['record']" class="filter-item fr" type="primary" @click="$router.push({path:'/user/member/disableRecord'})">操作记录</el-button>
    </div>
    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border highlight-current-row>
      <el-table-column align="center" label="手机号" prop="mobile"></el-table-column>
      <el-table-column align="center" label="昵称" prop="nickname"></el-table-column>
      <el-table-column align="center" label="性别">
        <template slot-scope="scope">
          <span v-text="sexes[scope.row.sex]"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="会员等级" prop="currentMemberCardType">
        <template slot-scope="scope">
          <a v-if="rightsButtons['level']" style="color: #409eff;" @click="leveClick(scope.row)">{{levels[scope.row.currentMemberCardType]}}</a>
          <span v-else>{{levels[scope.row.currentMemberCardType]}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="到期时间" prop="expireDate">
        <template slot-scope="scope">
          <span v-if="scope.row.currentMemberCardType != 3">{{formatDate(scope.row.expireDate, 'YYYY-MM-DD HH:mm:ss')}}</span>
          <span v-else>终身</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="注册时间">
        <template slot-scope="scope">
          <div class="text-justify">
            <p v-text="formatDate(scope.row.createdAt, 'YYYY-MM-DD HH:mm:ss')"></p>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="最后登录时间">
        <template slot-scope="scope">
          <div class="text-justify">
            <p v-text="formatDate(scope.row.lastLoginTime, 'YYYY-MM-DD HH:mm:ss')"></p>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.deleteFlag === 0">已禁用</span>
          <span v-if="scope.row.deleteFlag === 1">正常</span>
          <span v-if="scope.row.deleteFlag === 2">已注销</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否允许登录">
        <template slot-scope="scope">
          <span v-text="scope.row.deleteFlag === 1 ? '允许' : '不允许'"></span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180" v-if="rightsButtons['operate']||rightsButtons['level']||rightsButtons['upLevel']||rightsButtons['weChat']||rightsButtons['detail'] || rightsButtons['operate']">
        <template slot-scope="scope">
          <el-button v-if="rightsButtons['detail']" type="primary" size="mini" @click="$router.push({name: 'memberDetail', params: {id: scope.row.id}})">查看</el-button>
          <template v-if="rightsButtons['operate']">
            <el-button type="danger" v-if="scope.row.deleteFlag===1" size="mini" @click="operate(scope.row.id, 0, scope.row.subdivisionLevel)" plain>禁用</el-button>
            <el-button type="success" v-else size="mini" @click="initiateSet(scope.row.id, 1, scope.row.subdivisionLevel)" plain>启用</el-button>
          </template>
          <template v-if="rightsButtons['upLevel']">
            <el-button v-if="scope.row.currentMemberCardType != 3" type="infor" size="mini" @click="upLevel(scope.row)">升级董事</el-button>
          </template>
          <template v-if="rightsButtons['weChat']">
            <el-button type="success" size="mini" @click="untieWeChat(scope.row)" plain v-show="scope.row.wechatUnionid">微信解绑</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" v-if="total > 0">
      <el-pagination @current-change="handleCurrentChange" :current-page.sync="page" :page-size="pageSize" :total="total" layout="total, prev, pager, next, jumper"></el-pagination>
    </div>
    <el-dialog title="禁用" :visible.sync="showEditPop">
      <el-form :model="editItem"  :rules="commonRules"  size="medium" ref="editItem" label-width="120px">
        <el-form-item label="操作账号:">
           <span>{{userData.realname}}</span>
        </el-form-item>
        <el-form-item label="钉钉审批号:" prop="dingDingNo" :rules="commonRules.notNullRule">
            <el-input
              placeholder="请输入钉钉审批号"
              v-model="editItem.dingDingNo"
            >
            </el-input>
        </el-form-item>
        <el-form-item label="提交申请者:" prop="proposer" :rules="commonRules.notNullRule">
            <el-input
              placeholder="请输入申请者"
              v-model="editItem.proposer"
            >
            </el-input>
        </el-form-item>
        <el-form-item label="禁用原因:" prop="reason" :rules="commonRules.notNullRule">
            <el-input
              placeholder="请输入禁用原因"
              v-model="editItem.reason"
              type="textarea"
            >
            </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="disabledBtn" @click="disabledSet">禁用</el-button>
          <el-button @click="showEditPop = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="等级变更记录" :visible.sync="level_dialog_flag" @close="close">
      <el-table :data="level_dialog_data" v-loading="level_dialog_loading" element-loading-text="给我一点时间" border
        highlight-current-row
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}">
        <el-table-column prop="nickName" label="昵称">
        </el-table-column>
        <!-- <el-table-column prop="mobile" label="手机号码"></el-table-column> -->
        <el-table-column prop="beforeLevel" label="变更前等级">
          <template slot-scope="scope">
            {{levels[scope.row.beforeLevel]}}
          </template>
        </el-table-column>
        <el-table-column prop="afterLevel" label="变更后等级">
          <template slot-scope="scope">
            {{levels[scope.row.afterLevel]}}
          </template>
        </el-table-column>
        <el-table-column prop="changeType" label="变更类型"></el-table-column>
        <el-table-column prop="changeTime" label="变更时间"></el-table-column>
        <el-table-column prop="operator" label="操作人"></el-table-column>
        <el-table-column prop="remark" label="备注说明">
          <template slot-scope="scope">
            <span>{{scope.row.remark.split(",")[0]}}</span><br/>
            <img v-if="scope.row.remark.split(',')[1]" style="position: relative;width: 100px;height: 100px;" :src="scope.row.remark.split(',')[1]" alt="">
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container" v-if="level_total > 0">
        <el-pagination @current-change="handleCurrentChange_level" :current-page.sync="level_page" :page-size="level_pageSize" :total="level_total" layout="total, prev, pager, next, jumper"></el-pagination>
      </div>
    </el-dialog>
    <el-dialog title="升级董事" :visible.sync="upLevel_dialog_flag" @close="upLevelClose">
      <el-form class="privilege_manage_form" :model="upLevelForm" :rules="upLevelRules" size="medium" ref="upLevelForm" label-width="100px">
        <el-form-item label="昵称:" prop="iconUrl">
          <el-input disabled v-model="upLevelRow.nickname"/>
        </el-form-item>
        <el-form-item label="手机号:" prop="iconUrl">
          <el-input disabled v-model="upLevelRow.mobile"/>
        </el-form-item>
        <el-form-item label="图标:" prop="iconUrl">
          <el-upload class="avatar-uploader" accept="image/*" :action="upladUrl" name="file" :show-file-list="false"
            :on-success="uploadSuccess" :before-upload="beforeUpload">
            <img v-if="upLevelForm.iconUrl" :src="upLevelForm.iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input type="textarea" v-model="upLevelForm.remark" maxlength="120"></el-input>
        </el-form-item>
        <el-form-item prop="operator">
          <div class="operator">
            <el-button type="primary" @click="confirmUpLevel">升级</el-button>
            <el-button type="infor" @click="upLevel_dialog_flag = false">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="升级董事" :visible.sync="confirmUpLevel_dialog_flag">
      <div class="confirmUpLevel">
        <div>
          <span>昵称:{{upLevelRow.nickname}}&nbsp;&nbsp;{{upLevelRow.mobile}}</span>
        </div>
        <div class="confirmUpLevelImg">
          <span>图片:</span>
          <img v-if="upLevelForm.iconUrl" :src="upLevelForm.iconUrl" class="avatar" style="width: 100px;height: 100px;">
        </div>
        <div>
          <span>备注：{{upLevelForm.remark}}</span>
        </div>
        <div class="btn_group">
          <el-button type="primary" @click="confirmUpLevelAgain">确认升级</el-button>
        </div>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import {getUser} from '../../../utils/auth'
export default {
  name: 'member',
  data() {
    return {
      level_dialog_flag: false, //等级模态框状态
      level_dialog_loading: false, //等级模态框加载状态
      level_dialog_data: [], //等级列表数据
      level_row: '', //通过等级选中的row
      upLevel_dialog_flag: false, //升级董事的模态框状态
      confirmUpLevel_dialog_flag: false, //确认升级董事模态框状态
      upLevelRow: {}, //升级董事选中的row
      upLevelForm: {
        iconUrl: '',
        remark: ''
      }, //升级董事表单
      upLevelRules: {
        remark: [
            { required: true, message: '备注必填', trigger: 'blur' },
          ],
      },
      list: [],
      params: {
        search: '',
        currentMemberCardType: '',
        // role: '',
        nickname: '',
        realName: '',
        deleteFlag: ''
      },
      query: {},
      page: 1,
      pageSize: 20,
      total: 0,
      level_page: 1,
      level_pageSize: 10,
      level_total: 0,
      // 性别
      sexes: {
        '0': '保密',
        '1': '男',
        '2': '女'
      },
      // 会员等级
      levels: {},
      listLoading: false,
      btnDisabled: false,
      disabledBtn: false,
      editItem:{
        dingDingNo: '',
        proposer: '',
        reason: '',
        id: '',
        deleteFlag: '',
        subdivisionLevel: ''
      },
      showEditPop: false,
      userData: {}
    }
  },
  created() {
    //获取用户等级
    this.levels = this.$enum.vipGrade
    this.userData = getUser()
    this.getList()
  },
  methods: {
    //再次确认升级董事
    confirmUpLevelAgain() {
      this.request({
        url: '/bsnl-member/member/upgrade/partner',
        method: 'post',
        data: {
          remark: this.upLevelForm.remark+','+this.upLevelForm.iconUrl,
          userInfoId: this.upLevelRow.userId
        }
      }).then(res=>{
        console.log(res)
        if (res.status == 200) {
          this.confirmUpLevel_dialog_flag = false
          this.upLevel_dialog_flag = false
          this.getList()
          this.$message.success('升级成功!')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //确认升级董事
    confirmUpLevel() {
      this.$refs['upLevelForm'].validate((valid) => {
        if (valid) {
          this.confirmUpLevel_dialog_flag = true
        } else {
          this.$message.error('请填写备注!');
          return false;
        }
      });
    },
    //上传图片成功
    uploadSuccess(res) {
      this.upLevelForm.iconUrl = this.replaceImgUrl(res.filePath);
    },
    //上传图片前
    beforeUpload(file) {
      if (!/image/.test(file.type)) {
        this.$message.error('只能上传图片');
        return false;
      }
      if (file.size > 5120 * 5120) {
        this.$message.error('图片不能大于5M');
        return false;
      }
    },
    //关闭升级董事模态框
    upLevelClose() {
      this.$refs['upLevelForm'].resetFields();
    },
    //点击升级董事
    upLevel(row) {
      this.upLevelRow = row
      this.upLevel_dialog_flag = true
    },
    //关闭dialog
    close() {
      this.level_dialog_flag = false
      this.level_dialog_loading = false
      this.level_dialog_data = []
    },
    leveClick(row) {
      this.level_dialog_flag = true
      this.level_dialog_loading = true
      this.level_row = row
      this.getLevelData()
    },
    getLevelData() {
      this.request({
        url: `/bsnl-member/member/level/change/log/${this.level_row.userId}`,
        method: 'get',
        params: {
          pageNum: this.level_page,
          pageSize: this.level_pageSize
        }
      }).then(res=>{
        console.log(res)
        if (res.status == 200) {
          this.level_dialog_data = res.rows
          this.level_total = res.total
          this.level_dialog_loading = false
        }
      }).catch(err => {
        this.level_dialog_loading = false
      })
    },
    untieWeChat (row) {
      this.$confirm('您确认要微信解绑吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request({
          url: `/bsnl-member/member/wechatUnbind/${row.userId}`,
          method: 'get'
        }).then((res) => {
          if (res.success) {
            this.$message.success('解绑成功')
            this.getList()
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    // 获取列表
    getList() {
      this.listLoading = true
      this.request({
        url: '/bsnl-member/member/list',
        method: 'get',
        params: {
          offset: this.page - 1,
          limit: this.pageSize,
          ...this.query
        }
      })
        .then(({ rows, total }) => {
          this.list = rows
          this.total = total
          this.listLoading = false
        })
        .catch(err => {
          console.log(err)
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 搜索
    search() {
      this.page = 1
      this.query = { ...this.params }
      this.getList()
    },
    // 切换分页
    handleCurrentChange(page) {
      this.page = page
      this.getList()
    },
    handleCurrentChange_level(page) {
      this.level_page = page
      this.getLevelData()
    },
    disabledSet() {
      this.$refs.editItem.validate(valid => {
        if(valid) {
          this.$confirm(`确定禁用该用户`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.request({
              url: '/bsnl-member/member/changeDeleteFlag',
              method: 'post',
              data: this.editItem
            })
              .then(() => {
                 this.showEditPop = false
                this.getList()
                this.$message({
                  type: 'success',
                  message: '禁用成功'
                })
              })
              .catch(err => {
                console.log(err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
        }
      })
    },
    initiateSet(id, deleteFlag, subdivisionLevel) {
      this.editItem= {
        dingDingNo: '',
        proposer: '',
        reason: '',
        id: id,
        deleteFlag: deleteFlag,
        subdivisionLevel: subdivisionLevel?subdivisionLevel:0
      }
      this.$confirm(`确定启用该用户`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.request({
              url: '/bsnl-member/member/changeDeleteFlag',
              method: 'post',
              data: this.editItem
            })
              .then(() => {
                this.getList()
                this.$message({
                  type: 'success',
                  message: '启用成功'
                })
              })
              .catch(err => {
                console.log(err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            })
          })
    },
    operate(id, deleteFlag, subdivisionLevel) {
      this.editItem= {
        dingDingNo: '',
        proposer: '',
        reason: '',
        id: id,
        deleteFlag: deleteFlag,
        subdivisionLevel: subdivisionLevel?subdivisionLevel:0
      }
      if(deleteFlag===0) {
        this.showEditPop = true
      } else {
        this.showEditPop = false
      }
    }
  }
}
</script>

<style lang="scss" scoped="scoped">
  .confirmUpLevelImg {
    display: flex;
  }
  .confirmUpLevel div{
    margin: 20px 0;
  }
  .btn_group {
    display: flex;
    justify-content: center;
    padding-top: 20px;
  }
  .el-pagination {
    margin-right: 30px;
  }
</style>
